package com.tencent.supersonic.headless.server.task;

import java.sql.Connection;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson2.JSON;
import com.tencent.supersonic.headless.api.pojo.response.DatabaseResp;
import com.tencent.supersonic.headless.server.service.DatabaseService;

import ai.chat2db.spi.MetaData;
import ai.chat2db.spi.config.DBConfig;
import ai.chat2db.spi.sql.Chat2DBContext;
import ai.chat2db.spi.sql.ConnectInfo;
import ai.chat2db.spi.sql.ConnectionPool;
import ai.chat2db.spi.sql.IDriverManager;
import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class DbContextInitTask  implements CommandLineRunner {

	@Autowired
	private DatabaseService databaseService;
	
	@Override
	public void run(String... args) throws Exception {
		// TODO Auto-generated method stub
		/*
		List<DatabaseResp> list = databaseService.getDatabaseAll();
		
		log.info("databases:{}",JSON.toJSONString(list));
		for(DatabaseResp dataSource:list) {
			 ConnectInfo connectInfo = new ConnectInfo();
			 connectInfo.setDatabase(dataSource.getDatabase());
		     connectInfo.setSchemaName(dataSource.getSchema());
		     connectInfo.setDatabaseName(dataSource.getDatabase());
			 if(dataSource.getType().toLowerCase().equals("oracle")) {
				connectInfo.setUser(dataSource.getUsername().toUpperCase());
			 }else {
				connectInfo.setUser(dataSource.getUsername());
				// connectInfo.setDatabaseName("cpaasdev_admin_db");
			 }
		     connectInfo.setPassword(dataSource.getPassword());
		     connectInfo.setDbType(dataSource.getType().toUpperCase());
		     connectInfo.setUrl(dataSource.getUrl());
		     
		     connectInfo.setConsoleOwn(false);
		     connectInfo.setUrl(dataSource.getUrl());
		     connectInfo.setPort(StringUtils.isNotBlank(dataSource.getPort()) ? Integer.parseInt(dataSource.getPort()) : null);
		     connectInfo.setHost(dataSource.getHost());
		     log.info("id:{}",dataSource.getId());
		     try {
		    	 DBConfig dbConfig = Chat2DBContext.getDBConfig(dataSource.getType().toUpperCase());
				 if(null!=dbConfig) {
					 connectInfo.setDriver(dbConfig.getDefaultDriverConfig().getJdbcDriverClass());
					 connectInfo.setDriverConfig(dbConfig.getDefaultDriverConfig());
					 Chat2DBContext.putContext(connectInfo);
					 
					 log.info("info :{}",Chat2DBContext.getConnectInfo());
					 
					 
					 log.info("map:{},{}", JSON.toJSONString(Chat2DBContext.PLUGIN_MAP),Chat2DBContext.getConnectInfo().getDbType());
					 
					 // Chat2DBContext.PLUGIN_MAP.get(Chat2DBContext.getConnectInfo().getDbType()).getMetaData();
					 String db = getDataBaseName(dataSource.getUrl());
					 

					 log.info("db :{}",db);
					 
					 MetaData metaSchema = Chat2DBContext.getMetaData();
					 
					 log.info("scheam:{}",JSON.toJSONString(metaSchema));
					 
					 Connection connection = IDriverManager.getConnection(connectInfo.getUrl(), connectInfo.getUser(), connectInfo.getPassword(),
			                    connectInfo.getDriverConfig(), connectInfo.getExtendMap());
					 log.info("getDatabaseName:{},{},{}",connectInfo.getDatabaseName(),dataSource.getSchema(),dataSource.getDatabase());
					 String ddl = metaSchema.tableDDL(connection,  connectInfo.getDatabaseName(), connectInfo.getUser(), "ADMIN_USER");
					 
					 log.info("DDL:{}",JSON.toJSONString(ddl));
				 }
				 
				 //MetaData metaSchema = Chat2DBContext.getMetaData();
				 //log.info("meta:{}",metaSchema);
		     }catch(Exception e) {
		    	 
		     }
		     
		     
			 log.info("db:{},pass:{}",JSON.toJSONString(connectInfo),dataSource.getPassword());
			 
		}*/
	}
	
	public String getDataBaseName(String url) {
        Pattern p = Pattern.compile("jdbc:(?<db>\\w+):.*((//)|@)(?<host>.+):(?<port>\\d+)(/|(;DatabaseName=)|:)(?<dbName>\\w+.+)\\?");
        Matcher m = p.matcher(url);
        if(m.find()) {
            return m.group("dbName");
        }
        return null;
    }
	
	

}
